import dayjs from 'dayjs';

import { RESPONSE_CODE, RESPONSE_MSG } from '@/enums';
import type { Response } from '@/types';

/**
 * @description: 统一返回体
 */
export const responseMessage = <T = any>(
  data,
  msg: string = RESPONSE_MSG.SUCCESS,
  code: number = RESPONSE_CODE.SUCCESS,
): Response<T> => ({ data, msg, code, timestamp: dayjs().valueOf() });

export function crc32(input) {
  const crcTable = [];
  for (let i = 0; i < 256; i++) {
    let c = i;
    for (let j = 0; j < 8; j++) {
      if (c & 1) {
        c = 0xedb88320 ^ (c >>> 1);
      } else {
        c = c >>> 1;
      }
    }
    crcTable[i] = c;
  }

  let crc = 0 ^ -1;
  const buffer = new Uint8Array(input.length);
  for (let i = 0; i < input.length; i++) {
    buffer[i] = input.charCodeAt(i);
  }

  for (let i = 0; i < buffer.length; i++) {
    crc = (crc >>> 8) ^ crcTable[(crc ^ buffer[i]) & 0xff];
  }

  return (crc ^ -1).toString(16);
}
